﻿using MKAdmin.Web.Authorizes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using MKAdmin.Injection;
using System.Web.Mvc;
using MKAdmin.DTO.Web.Common;
using MKAdmin.IService.Web.Login;
using MKAdmin.IService.Web.Organization;

namespace MKAdmin.Web.Filters
{
    public class MvcAuthorize : System.Web.Mvc.AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException(nameof(filterContext));
            }
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                RedirectRouteUrl(filterContext, "100000");
                //filterContext.Result = new RedirectResult("/login");
                return;
            }

            // AllowAnonymousAttribute 允许匿名访问（跳过授权验证）
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
            filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                return;

            var curUser = CurrentUser.GetLoginInfo();
            var request = filterContext.HttpContext.Request;

            // 没有登录跳转到登录页面
            if (null == curUser || curUser.OperatorId <= 0)
            {
                RedirectRouteUrl(filterContext, "100000");
                return;
            }
            else
            {
                string areaName = filterContext.RouteData.DataTokens["area"] == null ? "" : filterContext.RouteData.DataTokens["area"].ToString();
                string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                string actionName = filterContext.ActionDescriptor.ActionName;

                string resourceName = $"{areaName}/{controllerName}/{actionName}";
                //获取功能权限
                if (!string.IsNullOrEmpty(areaName))
                {
                    var loginService = IOCFactory.GetService<ILoginService>();
                    //判断当前用户是否正常
                    if (loginService.VerifyUserStatus(curUser).status)
                    {
                        var permissionSetting = IOCFactory.GetService<IPermissionSettingService>();
                        var result = permissionSetting.UserPermissionVerify(resourceName, curUser);
                        if (!result.data)
                        {
                            RedirectRouteUrl(filterContext, "100001");
                        }
                    }
                    else
                    {
                        //退出登录
                        Loginer.SignOut();
                        filterContext.Result = new RedirectResult("/login");
                        return;
                    }
                }
            }

        }

        private static void RedirectRouteUrl(AuthorizationContext context, string code)
        {
            // 在跳转之前做判断,防止重复
            if (context.HttpContext.Response.IsRequestBeingRedirected) return;

            //判断是否为子操作或ajax请求if (context.IsChildAction || context.HttpContext.Request.IsAjaxRequest())
            if (context.HttpContext.Request.IsAjaxRequest())
            {
                //100000: 没有登录
                //100001: 没有权限
                var result = new Result { status = false, msg = code };
                context.Result = new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            else if (context.IsChildAction)
            {
                context.Result = new EmptyResult();
            }
            else
            {
                context.Result = new RedirectResult("/login");
            }
        }
    }
}